package com.zhongshengnetwork.rightbe;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WidgetModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.HashMap;

import static android.appwidget.AppWidgetManager.ACTION_APPWIDGET_UPDATE;

/**
 * Implementation of App Widget functionality.
 */
public class NewAppWidget extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        //Log.e("TAG","唯一langid广播="+intent.getAction());
        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (flag == true && CommonUtils.isLogin() == false ){
            return;
        }

        if (ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) {

            final HashMap<String, String> map = new HashMap<String, String>();
            if (ACTION_APPWIDGET_UPDATE.equals(intent.getAction())){//捕获系统自动更新通知
                map.put("auto", "0");
            }else {
                map.put("auto", "1");
            }
            //map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
            HttpsUtils.miniAppDo(map, "miniapp/widget.do", new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        WidgetModel widgetModel = GsonTools.getWidgetModel(data);
                        if (widgetModel != null && !CommonUtils.isEmpty(widgetModel.getTitle())){
                            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

                            RemoteViews remoteViews;
                            ComponentName watchWidget;

                            remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
                            watchWidget = new ComponentName(context, NewAppWidget.class);
                            remoteViews.setTextViewText(R.id.appwidget_text, widgetModel.getTitle());

                            // 添加响应事件
                            Intent intent = new Intent(context, SplashActivity.class);
                            intent.putExtra("langid", widgetModel.getLangid());
                            //Log.e("TAG","2唯一langid="+widgetModel.getLangid());
                            PendingIntent Pintent;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
                                Pintent = PendingIntent
                                        .getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
                            }else {
                                Pintent = PendingIntent
                                        .getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            }
                            remoteViews.setOnClickPendingIntent(R.id.appwidget_title, Pintent);
                            remoteViews.setOnClickPendingIntent(R.id.appwidget_text, Pintent);

                            Intent syncIntent = new Intent(ACTION_APPWIDGET_UPDATE);
                            PendingIntent syncPend;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
                                syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
                            }else {
                                syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                            }
                            remoteViews.setOnClickPendingIntent(R.id.appwidget_repeat, syncPend);//点击事件

                            appWidgetManager.updateAppWidget(watchWidget, remoteViews);
                        }
                    }
                }

                @Override
                public void onError(String msg) {

                }
            });


        }
    }

    void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

        /*
        // 添加响应事件
        Intent intent = new Intent(context, SplashActivity.class);
        PendingIntent Pintent = PendingIntent
                .getActivity(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.appwidget_title, Pintent);
        views.setOnClickPendingIntent(R.id.appwidget_text, Pintent);
        */

        //views.setOnClickPendingIntent(R.id.appwidget_repeat, getPendingSelfIntent(context, SYNC_CLICKED));//点击事件
        Intent syncIntent = new Intent(ACTION_APPWIDGET_UPDATE);
        PendingIntent syncPend;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
        }else {
            syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        views.setOnClickPendingIntent(R.id.appwidget_repeat, syncPend);//点击事件

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (flag == true && CommonUtils.isLogin() == false ){
            return;
        }

        //这里从服务器请求一次数据，开一个新接口：第一次获取当天排行第一的那条（随机返回50个字符以下的内容，30个点赞以上的轮播内容）
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("auto", "0");
        //map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        HttpsUtils.miniAppDo(map, "miniapp/widget.do", new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    WidgetModel widgetModel = GsonTools.getWidgetModel(data);
                    if (widgetModel != null && !CommonUtils.isEmpty(widgetModel.getTitle())){
                        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
                        views.setTextViewText(R.id.appwidget_text, widgetModel.getTitle());


                        // 添加响应事件
                        Intent intent = new Intent(context, SplashActivity.class);
                        intent.putExtra("langid", widgetModel.getLangid());
                        //Log.e("TAG","1唯一langid="+widgetModel.getLangid());
                        //E4EF5F5003314BE09409C546F51B5CB7
                        PendingIntent Pintent;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
                            Pintent = PendingIntent
                                    .getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
                        }else {
                            Pintent = PendingIntent
                                    .getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        }
                        views.setOnClickPendingIntent(R.id.appwidget_title, Pintent);
                        views.setOnClickPendingIntent(R.id.appwidget_text, Pintent);

                        Intent syncIntent = new Intent(ACTION_APPWIDGET_UPDATE);
                        PendingIntent syncPend;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
                            syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
                        }else {
                            syncPend = PendingIntent.getBroadcast(context, 0, syncIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        }
                        views.setOnClickPendingIntent(R.id.appwidget_repeat, syncPend);//点击事件

                        appWidgetManager.updateAppWidget(appWidgetId, views);
                    }
                }
            }

            @Override
            public void onError(String msg) {
            }
        });
        //通过广播传递点击事件：https://www.itranslater.com/qa/details/2583871063260136448
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

}

